﻿namespace Admin.NET.Application.Service;


/// <summary>
/// 基于EntityBaseId实体的服务基类, 实体没有审计字段
/// </summary>
[ApiDescriptionSettings(KeepName = true)]
public abstract class BaseServiceString<T> : IDynamicApiController where T : EntityBaseStringId, new()
{
    protected readonly SqlSugarRepository<T> _rep;

    public BaseServiceString(SqlSugarRepository<T> rep)
    {
        _rep = rep;
    }

    public ISugarQueryable<T> Queryable
    {
        get
        {
            return _rep.AsQueryable();
        }
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    protected T AddWithInput(object input)
    {
        var entity = input.Adapt<T>();
        // 判断Id是否存在
        var count = Queryable.Where(it => it.Id == entity.Id).Count();
        if (count > 0) throw new Exception("资料已存在");

        return _rep.InsertReturnEntity(entity);
    }

    /// <summary>
    /// 修改
    /// </summary>
    protected bool UpdateWithInput(object input)
    {
        return _rep.Update(input.Adapt<T>());
    }

    /// <summary>
    /// 通过id查询实体
    /// </summary>
    /// <param name="id"></param>
    protected T SingleById(string id)
    {
        return _rep.InSingle(id);
    }

    /// <summary>
    /// 通过id查询Output
    /// </summary>
    /// <typeparam name="Tout"></typeparam>
    /// <param name="id"></param>
    protected Tout GetById<Tout>(string id)
    {
        var obj = _rep.InSingle(id);
        return obj.Adapt<Tout>();
    }

}